<template>
  <div class="edit-profile">
    <NavBar>
      <template #default>
        编辑个人信息
      </template>
    </NavBar>

    <!-- 头像编辑 -->
    <!-- 修改头像上传部分 -->
    <div class="edit-section">
      <div class="section-header">头像</div>
      <div class="avatar-edit">
        <el-avatar :size="80" :src="form.avatar" />
        <input
          type="file"
          ref="avatarInput"
          style="display: none"
          accept="image/jpeg,image/png"
          @change="handleFileChange"
        >
        <el-button
          type="primary"
          size="small"
          @click="$refs.avatarInput.click()"
        >
          更换头像
        </el-button>
      </div>
    </div>

    <!-- 基本信息编辑 -->
    <div class="edit-section">
      <div class="section-header">基本信息</div>
      <el-form :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio :label="0">未知</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <!-- 联系方式编辑 -->
    <div class="edit-section">
      <div class="section-header">联系方式</div>
      <el-form :model="form" label-width="80px">
        <el-form-item label="手机号">
  <el-input v-model="form.mobile" placeholder="请输入手机号" readonly />
</el-form-item>
<el-form-item label="邮箱">
  <el-input v-model="form.email" placeholder="请输入邮箱" readonly />
</el-form-item>
      </el-form>
    </div>

    <!-- 保存按钮 -->
    <div class="save-btn" @click="handleSave">
      保存修改
    </div>
  </div>
</template>

<script setup>
import NavBar from '../../components/common/NavBar.vue';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
// 引入API
import { updateAvatar, updateUser } from '@/api/UserApi';
import { useUserStore } from '@/stores/userStore';

const router = useRouter();
const userStore = useUserStore();

// 从本地存储获取用户信息并初始化表单
// const userInfo = JSON.parse(localStorage.getItem('userAccount')) || {};
const userInfo = userStore.userAccount;
const form = ref({
  avatar: userInfo.avatar || '',
  userName: userInfo.userName || '',
  gender: userInfo.gender || 0,
  mobile: userInfo.mobile || '',
  email: userInfo.email || ''
});

// 处理文件选择
const handleFileChange = async (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 验证文件
  if (!validateFile(file)) return;

  try {
    // 创建FormData
    const formData = new FormData();
    formData.append('avatar', file);
    formData.append('userId', userInfo.userId);

    // 调用API上传
    const res = await updateAvatar(formData);

    // 更新前端显示
    form.value.avatar = res.data;
    userInfo.avatar = res.data;
    // localStorage.setItem('userAccount', JSON.stringify(userInfo));
    userStore.updateUserInfo({
      avatar: res.data,
    })

    ElMessage.success('头像更新成功');
  } catch (error) {
    ElMessage.error(error.message || '头像上传失败');
  } finally {
    // 重置input，允许重复选择同一文件
    e.target.value = '';
  }
};

// 文件验证
const validateFile = (file) => {
  const isJPGorPNG = ['image/jpeg', 'image/png'].includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPGorPNG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 保存修改
const handleSave = async () => {
  try {
    const useId = userStore.userAccount.userId;
    const responseResult = await updateUser(useId, form.value);
    console.log("完整响应结果为：", responseResult);

    // 防止 null 报错，优雅处理
    const code = responseResult?.code;
    const msg = responseResult?.msg || '更新失败';

    if (code === 1) {
      ElMessage.success('个人信息更新成功');
      // 将字符串转化成对象
      // const userAccount = JSON.parse(localStorage.getItem('userAccount'));
      // userAccount.userName = form.value.userName;
      // userAccount.gender = form.value.gender;
      // localStorage.setItem('userAccount', JSON.stringify(userAccount));
      userStore.updateUserInfo({
        userName: form.value.userName,
        gender: form.value.gender,
      })
      setTimeout(() => {
        router.back();
      }, 1000);
    } else {
      console.warn("更新失败：", msg);
      ElMessage.error(msg);
    }
  } catch (error) {
    console.error("请求异常：", error);
    ElMessage.error(error.message || '请求异常');
  }
};

</script>

<style scoped>
.edit-profile {
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 60px;
}

/* 编辑区块样式 */
.edit-section {
  background-color: #fff;
  margin: 10px;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 15px;
}

.section-header {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

/* 头像编辑区域 */
.avatar-edit {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-uploader {
  display: flex;
  align-items: center;
}

/* 表单样式 */
.el-form {
  padding-top: 10px;
}

.el-form-item {
  margin-bottom: 15px;
}

/* 保存按钮 */
.save-btn {
  margin: 20px 15px;
  padding: 12px 0;
  background-color: #ff5000;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
}

.save-btn:active {
  opacity: 0.9;
}
</style>